package jp.co.sega.sonic_jump.monthly.sum;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.content.res.AssetManager;
import java.io.InputStream;
import java.io.IOException;
import android.content.res.AssetFileDescriptor;
import android.os.Build;
import android.media.AudioAttributes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DeviceSound implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener {
    public static int LastSound = 0;
    public static final int NUM_EXTRA_SFX = 18;
    public static final int SFX_MAX = 10;
    public static final int TYPE_MIDI = 0;
    private static Activity activity = null;
    private static AudioManager mAudioManager = null;
    private static int m_LastBgm = 0;
    public static MediaPlayer music = null;
    public static int musicwanted = 0;
    public static int qed = 0;
    public static int qedloop = 0;
    public static MediaPlayer[] sfx = new MediaPlayer[10];
    public static boolean[] sfx_available = new boolean[10];
    public static int[][] SOUNDS = {new int[]{-99}, new int[]{-3}, new int[]{-2}, new int[]{-1}, new int[]{0}, new int[]{1, 1}, new int[]{2, 2}, new int[]{3, 3}, new int[]{100, 4}, new int[]{101, 5}, new int[]{113, 6}, new int[]{114, 7}, new int[]{102, 8}, new int[]{111, 9}, new int[]{112, 10}, new int[]{103, 11}, new int[]{104, 12}, new int[]{105, 13}, new int[]{106, 14}, new int[]{107, 15}, new int[]{108, 16}, new int[]{109, 17}, new int[]{110, 18}, new int[]{115, 19}, new int[]{116, 20}, new int[]{117, 21}, new int[]{118, 22}};

    public DeviceSound() {
        activity = Shell.sInstance;
        mAudioManager = (AudioManager) activity.getSystemService("audio");
        for (int i = 0; i < 10; i++) {
            sfx_available[i] = true;
        }
    }
    
    public void downloadZip(final String urlString, final File outputFile, final DownloadCallback callback) throws IOException {
        new Thread(new Runnable() {
        @Override
        public void run() {
        try {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
    
        InputStream input = connection.getInputStream();
        FileOutputStream output = new FileOutputStream(outputFile);
    
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.close();
        input.close();
        connection.disconnect();
        callback.onSuccess();
        } catch (Exception e) {
        callback.onError(e);
        }
        }
        }).start();
    }
    
    public File extractAudioFromZip(File zipFile, File outputDir) throws IOException {
    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            if (!ze.isDirectory() && ze.getName().toLowerCase().endsWith(".mp3")) {
                File outFile = new File(outputDir, new File(ze.getName()).getName());
                try (FileOutputStream fos = new FileOutputStream(outFile)) {
                    byte[] buffer = new byte[4096];
                    int count;
                    while ((count = zis.read(buffer)) != -1) {
                        fos.write(buffer, 0, count);
                    }
                }
                return outFile;
            }
        }
    }
    return null;
}
    
    public void PlayMusic(String str, final boolean loop2) {
    try {
    if (str.endsWith(".zip")) {
            final File cache = Shell.sInstance.getCacheDir();
            final File tempFile = new File(cache, "temp.zip");

            downloadZip(str, tempFile, new DownloadCallback() {
                @Override
                public void onSuccess() {
                    try {
                        File mp3File = extractAudioFromZip(tempFile, cache);
                        if (mp3File == null) {
                            throw new IOException("No MP3 files found in ZIP");
                        }
                        startMediaPlayer(mp3File.getAbsolutePath(), loop2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            });
        } else {
            startMediaPlayer(str, loop2);
        }
    } catch (IOException e) {
      e.printStackTrace();
    }
    }
    
    private void startMediaPlayer(String str, boolean loop2) throws IOException {
        if (music != null) {
        music.stop();
        music.release();
        }
        music = new MediaPlayer();
        music.setDataSource(str);
        music.prepare();
        music.setVolume(0.05f,0.05f);
        music.setLooping(loop2);
        music.start();
        music.setOnCompletionListener(DeviceSound.this);
    }
    
    public interface DownloadCallback {
        void onSuccess();
        void onError(Exception e);
    }

    public static final void stopsfx(MediaPlayer player) {
        if (player != null) {
            try {
                player.stop();
                //player.setOnCompletionListener((MediaPlayer.OnCompletionListener) null);
                player.release();
            } catch (Exception e) {
                System.out.println("sound stop error " + e.toString());
            }
        }
    }

    private static int getMusic(int n) {
        int nReturn = 0;
        for (int k = 0; k < SOUNDS.length; k++) {
            if (SOUNDS[k].length > 1 && n == SOUNDS[k][0]) {
                nReturn = SOUNDS[k][1];
            }
        }
        return nReturn;
    }

    public static int getLastSound() {
        return LastSound;
    }

    public static int getQed() {
        return qed;
    }

    public void PlaySound(final int n, final int l) {
    Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        boolean loop;
        boolean loop2;
        int nPlay = getMusic(n);
        if (nPlay == 21) {
        Game_Draw.bluehoops += 1;
        }
        int ntmp = n;
        if (nPlay == 0) {
            if (music != null) {
                stopsfx(music);
            }
            LastSound = n;
            m_LastBgm = 0;
            return;
        }
        if (ntmp >= 100) {
            ntmp -= 96;
        }
        try {
        if (Game_Draw.tuneflags[ntmp - 1] != 1) {
                if (music != null) {
                    if (m_LastBgm != nPlay) {
                        stopsfx(music);
                    } else if (!music.isPlaying()) {
                        stopsfx(music);
                    } else {
                        return;
                    }
                }
                m_LastBgm = nPlay;
                LastSound = n;
                if (l == -1) {
                    loop2 = true;
                } else {
                    loop2 = false;
                }
                //music = MediaPlayer.create(activity, (R.raw.tune01 + nPlay) - 1);
                int resourceId = 0;
                boolean useAssets = false;
                String assetFileName = "";
                InputStream inputStream;
                if (Game_Draw.Online && nPlay >= 11 && nPlay <= 16 && Game_Draw.currentmusic != null && Game_Draw.currentmusic[Shell.sInstance.getCanvas().ssely] != null && !Game_Draw.currentmusic[Shell.sInstance.getCanvas().ssely].isEmpty()) {
                PlayMusic(Game_Draw.currentmusic[Shell.sInstance.getCanvas().ssely], loop2);
                return;
                }
try {
    if (!Game_Draw.JumpPro && !Game_Draw.Fever) {
        resourceId = activity.getResources().getIdentifier("tune" + String.format("%02d", nPlay), "raw", activity.getPackageName());
    } else {
        String ost = "";
        String P = "";
        if (Game_Draw.JumpPro) {
        ost = "Pro";
        P = "P";
        } else if (Game_Draw.Fever) {
        ost = "Fever";
        P = "F";
        }
        Game_Draw gd = Shell.sInstance.getCanvas();
        if (nPlay <= 10 || nPlay >= 17) {
        assetFileName = ost + "/tune" + P + String.format("%02d", nPlay) + ".m4a";
        } else {
        for (int j = 0; j < 7; j++) {
        //Game_Draw gd = Shell.sInstance.getCanvas();
            for (int k = 0; k < 3; k++) {
                if (gd.lsely == j && gd.lselx == k) {
                int kk = k;
                    if (kk > 0) { 
                    kk = kk + 1; 
                    }
                    String ll = (k == 0) ? "" : "-" + kk;
                    int n = j == 6 ? 10 : 11;
                    assetFileName = ost + "/tune" + P + String.format("%02d", j + n) + ll + ".m4a";
                    try (InputStream testStream = activity.getAssets().open(assetFileName)) {
                    useAssets = true;
        } catch (IOException e) {
            assetFileName = ost + "/tune" + P + String.format("%02d", j + n) + ".m4a";
        }
                    break;
                }
            }
        }
        }

        // Verifica se o arquivo existe
        try (InputStream testStream = activity.getAssets().open(assetFileName)) {
            if (!useAssets) {
            useAssets = true;
            }
        } catch (IOException e) {
            resourceId = activity.getResources().getIdentifier("tune" + String.format("%02d", nPlay), "raw", activity.getPackageName());
        }
    }

    if (!useAssets) {
        music = MediaPlayer.create(activity, resourceId);
        if (Build.VERSION.SDK_INT < 26) {
        music.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } else {
        music.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
               }
        setVolume(music, isSilent());
    } else {
        if (music != null) {
        music.release();
        }
        music = new MediaPlayer();
        /*if (Build.VERSION.SDK_INT < 26) {
        music.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } else {
        music.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
               }*/
        AssetFileDescriptor afd = activity.getAssets().openFd(assetFileName);
        music.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        music.prepare();
    }

    music.setLooping(loop2);
    music.start();
    music.setOnCompletionListener(DeviceSound.this);
    if (useAssets) {
    soundtrackVolume();
    }
} catch (IOException e) {
    e.printStackTrace(); // Log do erro
}
                return;
        }
            for (int i = 0; i < 10; i++) {
                if (sfx_available[i]) {
                    if (l == -1) {
                        loop = true;
                    } else {
                        loop = false;
                    }
                    int resourceId;
                    resourceId = activity.getResources().getIdentifier("tune" + String.format("%02d", nPlay), "raw", activity.getPackageName());
                    sfx[i] = MediaPlayer.create(activity, resourceId);
                    //sfx[i] = MediaPlayer.create(activity, (R.raw.tune01 + nPlay) - 1);
                    sfx[i].setLooping(loop);
                    sfx[i].setAudioStreamType(3);
                    sfx[i].setOnCompletionListener(DeviceSound.this);
                    setVolume(sfx[i], isSilent());
                    sfx[i].start();
                    sfx_available[i] = false;
                    return;
                }
            }
        } catch (Exception e) {
                System.out.println("sfx error " + e.toString());
        }
        }
});
thread.start();
    }

    public static void setVolume(MediaPlayer mp, boolean isSilent) {
        if (mp != null) {
            try {
                if (isSilent) {
                    mp.setVolume(0.0f, 0.0f);
                } else {
                    mp.setVolume(1.0f, 1.0f);
                }
            } catch (Exception e) {
            }
        }
    }
    
    public static void soundtrackVolume() {
    if (music != null) {
        try {
        music.setVolume(1.0f, 1.0f);
        } catch (Exception e) {
        }
     }
  }

    public static void setSilent() {
        boolean isSilent = isSilent();
        if (!Game_Draw.JumpPro && !Game_Draw.Fever) {
        setVolume(music, isSilent);
        } else {
        soundtrackVolume();
        }
        for (int i = 0; i < 10; i++) {
            if (!sfx_available[i]) {
                setVolume(sfx[i], isSilent);
            }
        }
    }

    public static boolean isSilent() {
        /*if (mAudioManager.getRingerMode() == 0 || mAudioManager.getRingerMode() == 1) {
            return true;
        }*/
        return false;
    }

    public static void PlayStoredSound() {
    }

    public static void releaseAll() {
        stopsfx(music);
        for (int i = 0; i < 10; i++) {
            if (sfx[i] != null) {
                stopsfx(sfx[i]);
            }
            sfx_available[i] = true;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        for (int i = 0; i < 10; i++) {
            if (mp.equals(sfx[i])) {
                sfx_available[i] = true;
            }
        }
        stopsfx(mp);
    }
   
    @Override
    public void onPrepared(MediaPlayer mp) {
        //mp.start();
    }
}
